from flask import Flask, session, g, request, redirect, url_for
import config
from exts import db, mail, login_manager, csrf
from models import UserModel
from blueprints.ec import bp as ec_bp
from blueprints.auth import bp as auth_bp
from blueprints.pr import bp as pr_bp
from blueprints.answer import bp as answer_bp
from flask_migrate import Migrate
from datetime import datetime

app = Flask(__name__)
app.config.from_object('config')  # 加载配置
app.config['SECRET_KEY'] = '<tyghyhujfrdsxcv@jhyhft'  # 替换为随机字符串


# 添加 datetimeformat 过滤器
@app.template_filter('datetimeformat')
def datetimeformat(value, format='%Y-%m-%d %H:%M:%S'):
    if value is None:
        return ""
    return value.strftime(format)


# 初始化扩展
db.init_app(app)
mail.init_app(app)
csrf.init_app(app)
login_manager.init_app(app)
login_manager.login_view = 'auth.login'  # 设置登录视图

migrate = Migrate(app, db)

# 注册 Blueprint
csrf.exempt(ec_bp)
app.register_blueprint(ec_bp)

app.register_blueprint(auth_bp)
app.register_blueprint(pr_bp)
app.register_blueprint(answer_bp)


# from flask_cors import CORS
# CORS(app)  # 允许所有域名跨域访问

# blueprint:用来做模块化的
# 电影、谈书、音乐、xxx

# flask db init: 只需要执行一次
# flask db migrate: 将orm模型生成迁移脚本
# flask db upgrade: 将迁移脚本映射到数据库中

# before_request/ before_first_request/ after_request
# hook

# 钩子函数
@app.before_request
def before_request():
    # 允许访问的公开路由
    public_routes = ['auth.login', 'auth.register', 'auth.get_email_captcha',
                     'auth.get_image_captcha', 'ec.index', 'static']

    user_id = session.get('user_id')
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, 'user', user)
    else:
        setattr(g, 'user', None)
        # 根路由和静态资源允许访问
        if request.endpoint not in public_routes and not request.path.startswith('/static/'):
            return redirect(url_for('auth.login'))


@app.context_processor
def my_context_processor():
    return {"user": g.user}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8001)
